﻿using Furion;
using Jiffy.Common.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Serilog;

namespace Jiffy.Middle.Basics
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // 添加数据库
            //services.AddDatabaseAccessor(opt =>
            //{
            //    opt.CustomizeMultiTenants();
            //    opt.AddDbPool<AuthDbContext, AuthDbContextLocator>(providerName: default, _opt =>
            //    {
            //        _opt.UseBatchEF_MySQLPomelo();
            //    });
            //    opt.AddDbPool<SysDbContext, SysDbContextLocator>(providerName: default, _opt =>
            //    {
            //        _opt.UseBatchEF_MySQLPomelo();
            //    });
            //    opt.AddDbPool<LogDbContext, LogDbContextLocator>(providerName: default, _opt =>
            //    {
            //        _opt.UseBatchEF_MySQLPomelo();
            //    });
            //}, "Jiffy.Migrations");

            // 注册RefreshToken配置
            //services.AddConfigurableOptions<RefreshTokenSettingOptions>();
            // 注册Jwt
            //services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);

            // 配置跨域
            services.AddCorsAccessor();

            // 注册远程请求
            services.AddRemoteRequest();

            // 注册基础组件
            var controllers = services.AddControllers();

            // 默认Json格式
            controllers.AddNewtonsoftJson(options =>
            {
                // 首字母小写(驼峰样式)
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                // 时间格式化
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                // 忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                // 忽略空值
                // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            // 规范化返回值
            controllers.AddInjectWithUnifyResult<XnRestfulResultProvider>();

            // 注册试图引擎
            //services.AddViewEngine();

            // 注册SignalR
            //services.AddSignalR();

            // 注册事件总线
            //services.AddEventBridge();

            // 注册缓存
            //if (App.Configuration["Cache:CacheType"] == "RedisCache")
            //{
            //    services.AddStackExchangeRedisCache(options =>
            //    {
            //        options.Configuration = App.Configuration["Cache:RedisConnectionString"]; // redis连接配置
            //        options.InstanceName = App.Configuration["Cache:InstanceName"]; // 键名前缀
            //    });
            //}

            //// default minio
            //// 添加默认对象储存配置信息
            //services.AddOSSService(option =>
            //{
            //    option.Provider = OSSProvider.Minio;
            //    option.Endpoint = "oss.oncemi.com:9000";
            //    option.AccessKey = "Q*************9";
            //    option.SecretKey = "A**************************Q";
            //    option.IsEnableHttps = true;
            //    option.IsEnableCache = true;
            //});

            // aliyun oss
            // 添加名称为‘aliyunoss’的OSS对象储存配置信息
            //services.AddOSSService("aliyunoss", option =>
            //{
            //    option.Provider = OSSProvider.Aliyun;
            //    option.Endpoint = "oss-cn-hangzhou.aliyuncs.com";
            //    option.AccessKey = "L*******************U";
            //    option.SecretKey = "5*******************************T";
            //    option.IsEnableCache = true;
            //});

            //// qcloud oss
            //// 从配置文件中加载节点为‘OSSProvider’的配置信息
            //services.AddOSSService("QCloud", "OSSProvider");
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                // 显示异常信息页
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 错误页跳转
                app.UseExceptionHandler("/Home/Error");

                // 采用严格传输模式
                app.UseHsts();
            }

            // NGINX 反向代理获取真实IP
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            // 添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();

            // 强制使用https
            app.UseHttpsRedirection();

            // 使用静态资源文件
            app.UseStaticFiles();

            // Serilog请求日志中间件---必须在 UseStaticFiles 和 UseRouting 之间
            app.UseSerilogRequestLogging();

            // 使用路由功能
            app.UseRouting();

            // 添加跨域
            app.UseCorsAccessor();

            // 添加用户认证
            app.UseAuthentication();

            // 添加鉴权
            app.UseAuthorization();

            // 注入Furion基础件
            app.UseInject(string.Empty);

            // 定义默认路由
            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapHub<ChatHub>("/hubs/chathub");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            //// 设置雪花Id的workerId，确保每个实例workerId都应不同
            //var workerId = ushort.Parse(App.Configuration["SnowId:WorkerId"] ?? "1");
            //YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = workerId });

            //// 开启自启动定时任务
            ////App.GetService<ISysTimerService>().StartTimerJob();
        }
    }
}